package leetcode.D2000.T1905;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: 18362
 * @Create: 2022-02-26 17:09:41 星期六
 */
class Solution {
    private static final int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid1.length, n = grid1[0].length, num = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid1[i][j]==0 && grid2[i][j]==1)
                    dfs(grid2, i, j);
            }
        }
        for(int i=0; i<m; ++i) {
            for (int j = 0; j < n; j++) {
                if (grid2[i][j] == 1) {
                    num++;
                    dfs(grid2, i, j);
                }
            }
        }
        return num;
    }

    private void dfs(int[][] grid, int row, int col) {
        grid[row][col] = 0;
        int m = grid.length, n = grid[0].length;
        for (int[] dir : dirs) {
            int x = row + dir[0], y = col + dir[1];
            if (x>=0 && x<m && y>=0 && y<n && grid[x][y]==1)
                dfs(grid, x, y);
        }
    }
}